<?php

namespace app\login\controller;

use think\Request;
use think\Controller;
use think\Db;
use think\Route;
use think\Url;
use think\Validate;
use think\Cache;
use think\Session;
use app\index\controller\Index;



use app\model\model\User;

//引入User模型
use app\model\model\Pay;

//引入Pay模型
use app\model\model\Order;

//引入Order模型
use app\model\model\Core;

//引入Core模型
use app\model\model\Captcha;

//引入Captcha模型
use app\model\model\Login;

//引入Login模型
class Qqlogin extends Controller
{
    private $appid = 'wx9f20558a2e9462df';
    private $appsecret = '08e798f6d0ac073405add12ada18c6c6';
    private $redirect_uri = 'https://www.cuupay.com/login/qqlogin/getLogin';

    public function index(Request $request)
    {
        if (isLogin('user')) {
            exit("<script language='javascript'>window.location.href='/user';</script>");
        }

        $core = Core::where('id', '<>', 0)->column('value1', 'name');
        if($core['veloce_qqlogin']!=1){
            exit("<script language='javascript'>alert('抱歉，暂未开放微信快捷登录方式！');window.location.href='/login';</script>");
        }
        $this->assign('title', '微信快捷登录');  //输出变量

        $this->assign('core', $core);  //输出变量
        return $this->fetch('qqlogin/index');  //进入模板
    }

    // 处理支付宝添加信息
    public function addAlipay(Request $request)
    {

        if(strpos($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST'])===false){
            return json_encode(array('code'=>-1,'msg'=>'非法操作'));
        }
        $postArray = $request->post();
        if (!array_key_exists('uid', $postArray)) {
            return json_encode(array("code"=>-1,"msg"=>"uid不能为空"));
        }
        if (!array_key_exists('datamsg', $postArray)) {
            return json_encode(array("code"=>-1,"msg"=>"datamsg不能为空"));
        }
        $uid = $postArray['uid'];
        $data =  $postArray['datamsg'];
        $user = User::getByUid($uid);
        if ($user) {
            //注册用户，绑定微信
            return isalipayUser(['uid' => $uid,"data"=>$data]);
        }else{
            return ['code' => -1, 'msg' => '未登录'];
        }
    }



    // 微信扫码回调处理
    public function getLogin(Request $request)
    {
        $state = $request->get('state');
        if (!$state) {
            exit("<script language='javascript'>alert('微信授权失败');window.location.href='/register';</script>");
        }
        $code = $request->get('code');
        if (!$code) {
            exit("<script language='javascript'>alert('微信授权失败');window.location.href='/register';</script>");
        }

        // 通过code获取access_token
        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code";
        $token_data = json_decode($this->get_curl($token_url), true);

        if (isset($token_data['errcode'])) {
            exit("<script language='javascript'>alert('获取微信授权失败');window.location.href='/register';</script>");
        }
        $openid = $token_data['openid'];

        // 处理登录逻辑
        $arr = $this->handleLogin($openid);
        if($arr['code']!=0){
            $arrText =  $arr['msg'];
            exit("<script language='javascript'>alert($arrText);window.location.href='/register';</script>");
        }else{
            Cache::set($state, $openid, 300); // 5分钟过期
            return $this->fetch('qqlogin/success');
        }
    }


    public function paySuccess(Request $request)
    {
        return $this->fetch('qqlogin/success');
    }

    // 处理登录逻辑
    private function handleLogin($openid)
    {
        $user = User::where("veloce_qq", $openid)->find();
        if (!$user) {
            //注册用户，绑定微信$value1
            return isWxUser(['veloce_qq' => $openid,"ismd5"=>"",]);
        }else{
            return ['code' => 0, 'msg' => '已登录'];
        }
    }
    // 获取微信二维码
    public function getqr(){
        if(strpos($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST'])===false){
            return json_encode(array('code'=>-1,'msg'=>'非法操作'));
        }
        $state = md5(time().rand(1000,9999));
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.
            '&redirect_uri='.urlencode($this->redirect_uri).
            '&response_type=code&scope=snsapi_base&state='.$state.'#wechat_redirect';

        return json_encode(array('code' => 0,  'data' => $url,'qrsig' => $state));

    }

    private function get_curl($url,$post=0,$referer=0,$cookie=0,$header=0,$ua=0,$nobaody=0,$split=0){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $httpheader[] = "Accept: application/json";
        $httpheader[] = "Accept-Encoding: gzip,deflate,sdch";
        $httpheader[] = "Accept-Language: zh-CN,zh;q=0.8";
        $httpheader[] = "Connection: close";
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
        if($post){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        if($header){
            curl_setopt($ch, CURLOPT_HEADER, TRUE);
        }
        if($cookie){
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }
        if($referer){
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }
        if($ua){
            curl_setopt($ch, CURLOPT_USERAGENT,$ua);
        }else{
            curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36');
        }
        if($nobaody){
            curl_setopt($ch, CURLOPT_NOBODY,1);

        }
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        $ret = curl_exec($ch);
        if ($split) {
            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $header = substr($ret, 0, $headerSize);
            $body = substr($ret, $headerSize);
            $ret=array();
            $ret['header']=$header;
            $ret['body']=$body;
        }
        curl_close($ch);
        return $ret;
    }
    private function getqrtoken($qrsig){
        $len = strlen($qrsig);
        $hash = 0;
        for($i = 0; $i < $len; $i++){
            $hash += (($hash << 5) & 2147483647) + ord($qrsig[$i]) & 2147483647;
            $hash &= 2147483647;
        }
        return $hash & 2147483647;
    }
    private function isqrsig($qrsig,$sig="星益云"){
        if(strpos($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST'])===false){
            return array('code'=>-1,'msg'=>'非法操作');
        }
        if(empty($qrsig)){
            return array('code'=>-1,'msg'=>'qrsig不能为空');
        }
        $url='https://ssl.ptlogin2.qq.com/ptqrlogin?u1=https%3A%2F%2Fgraph.qq.com%2Foauth2.0%2Flogin_jump&ptqrtoken='.$this->getqrtoken($qrsig).'&ptredirect=0&h=1&t=1&g=1&from_ui=1&ptlang=2052&action=0-0-'.time().'0000&js_ver=21020514&js_type=1&login_sig='.$sig.'&pt_uistyle=40&aid=716027609&daid=383&pt_3rd_aid=101487368&';
        $ret = $this->get_curl($url,0,$url,'qrsig='.$qrsig.'; ',1);
        if(preg_match("/ptuiCB\('(.*?)'\)/", $ret, $arr)){
            $r=explode("','",str_replace("', '","','",$arr[1]));
            if($r[0]==0){
                preg_match('/uin=(\d+)&/',$ret,$uin);
                $uin=$uin[1];
                return array('code'=>0,'uin'=>$uin,'nickname'=>$r[5]);
            }elseif($r[0]==65){
                return array('code'=>4,'msg'=>'二维码已失效！');
            }elseif($r[0]==66){
                return array('code'=>2,'msg'=>'请打开手机微信扫描二维码...');
            }elseif($r[0]==67){
                return array('code'=>3,'msg'=>'正在验证二维码...');
            }else{
                return array('saveOK'=>6,'msg'=>$r[4]);
            }
        }else{
            return array('saveOK'=>6,'msg'=>$ret);
        }
    }
    //验证身份 (保持原有接口但修改实现)
    public function islogin(Request $request){
        if(strpos($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST'])===false){
            return json_encode(array('code'=>-1,'msg'=>'非法操作'));
        }
        $core = Core::where('id', '<>', 0)->column('value1', 'name');
        if($core['veloce_qqlogin']!=1){
            return json_encode(array("code"=>-1,"msg"=>"抱歉，暂未开放微信快捷登录方式！"));
        }

        $postArray = $request->post();
        if (!array_key_exists('qrsig', $postArray)) {
            return json_encode(array("code"=>-1,"msg"=>"qrsig不能为空"));
        } else {
            $qrsig = $postArray['qrsig'];
            $opid = Cache::get($qrsig);
            // 登录成功了
            if($opid){
                $user = User::where("veloce_qq", $opid)->find();
                if ($user) {
                    // 方法一：使用 strpos 函数
                    if (strpos($user['nickname'], '支付宝') !== false) {
                        $strpos = '0';
                    } else {
                        // 不包含"支付宝"三个字
                        $strpos = '-1';
                    }
                    return json_encode(array("code"=>0,"strpos"=> $strpos,"nickname"=>$user['nickname'],"uid"=>$user['uid'],"apikey"=>$user['key'],"msg"=>"登录成功"));
                }else{
                    return json_encode(array("code"=>-1,"msg"=>"未查到用户"));
                }
            }else{
                return json_encode(array('code'=>3,'msg'=>'正在验证二维码...'));
            }
        }
    }
    //更换绑定 - 页面
    public function oper(Request $request)
    {
        if (!isLogin('user')) {
            exit("<script language='javascript'>window.location.href='/login';</script>");
        }
        $user = User::where('uid', getUserUid())->find();  //获取商户信息
        if (!$user) {
            exit("<script language='javascript'>alert('商户不存在或被删除');window.location.href='/user';</script>");
        }

        $get = $request->get();
        if(array_key_exists("relieve",$get)){
            if($user['veloce_qq']==NULL or trim($user['veloce_qq'])==""){
                exit("<script language='javascript'>alert('商户未绑定微信，无法解除绑定');window.location.href='/user';</script>");
            }
            $this->assign('title', '解除绑定');  //输出变量
            $this->assign('mode', 'relieve');  //输出变量
        }else{
            $this->assign('mode', 'replace');  //输出变量
            $this->assign('title', '更换绑定');  //输出变量
        }
        $core = Core::where('id', '<>', 0)->column('value1', 'name');

        $this->assign('core', $core);  //输出变量
        return $this->fetch('qqlogin/oper');  //进入模板
    }
    //更换绑定 - 业务逻辑
    //这个换绑改后清除旧数据
    public function oper_handle(Request $request){
        if(strpos($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST'])===false){
            return json_encode(array('code'=>-1,'msg'=>'非法操作'));
        }
        if (!isLogin('user')) {
            return json_encode(array("code"=>-1,"msg"=>"请先登录商户","url"=>"/login"));
        }
        $user = User::where('uid', getUserUid())->find();  //获取商户信息
        if (!$user) {
            return array("code" => -1, "msg" => "商户不存在或被删除","url"=>"/login");
        }

        $postArray = $request->post();
        if (!array_key_exists('qrsig', $postArray)) {
            return json_encode(array("code"=>-1,"msg"=>"qrsig不能为空"));
        } else {
            $qrsig = $postArray['qrsig'];
        }
        if (!array_key_exists('mode', $postArray)) {
            return json_encode(array("code"=>-1,"msg"=>"请选择操作方式"));
        } else {
            $mode = $postArray['mode'];
        }
        $arr = $this->isqrsig($qrsig);
        if($arr['code']!=0){
            return json_encode($arr);
        }
        $qq = $arr['uin'];

        if($mode == "replace") {
            if ($qq == $user['veloce_qq']) {
                return json_encode(array("code" => -1, "msg" => "该微信与您当前已绑定的微信一致，无需更换！", "url" => "/user"));
            }
            $temp = User::where("veloce_qq", $qq)->find();
            if ($temp) {
                return json_encode(array("code" => -1, "msg" => "该微信已与其他商户绑定，请先解除绑定！", "url" => "/user"));
            }
            $temp = User::getById($user['id']);
            $temp->veloce_qq = $qq;
            if ($temp->save() !== false) {
                return json_encode(['code' => 0, 'msg' => "更换成功", "url" => "/user"]);
            } else {
                return json_encode(['code' => -1, 'msg' => "更换失败", "url" => "/user"]);
            }
        }else if($mode=="relieve"){
            if ($qq != $user['veloce_qq']) {
                return json_encode(array("code" => -1, "msg" => "该微信与您当前已绑定的微信不一致，无法解除绑定！", "url" => "/user"));
            }
            $temp = User::getById($user['id']);
            $temp->veloce_qq = NULL;
            if ($temp->save() !== false) {
                return json_encode(['code' => 0, 'msg' => "解绑成功", "url" => "/user"]);
            } else {
                return json_encode(['code' => -1, 'msg' => "解绑失败", "url" => "/user"]);
            }
        }else{
            return json_encode(array("code"=>-1,"msg"=>"非法的操作方式"));
        }
    }
}